import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../components/Login.vue'
import Main from '../components/Main.vue'
import Register from '../components/Register.vue'
import Home from '../components/Home.vue'
import Select from '../components/Select.vue'
import History from '../components/History.vue'
import Question from '../components/Question.vue'
import AddOrEditQuestion from '../components/AddOrEditQuestion.vue'
import User from '../components/User.vue'
Vue.use(VueRouter)

const routes = [{
		path: '/',
		name: 'Login',
		component: Login,
		meta: {
			requiresAuth: false
		} // 明确不需要认证
	}, {
		path: '/register',
		name: 'register',
		component: Register,
		meta: {
			requiresAuth: false
		} // 明确不需要认证
	},
	{
		path: '/main',
		name: 'Main',
		component: Main,
		meta: {
			requiresAuth: true
		}, // 需要认证
		redirect: 'main/select',
		children: [{
				path: 'select',
				name: 'Select',
				component: Select
			},
			{
				path: 'history',
				name: 'History',
				component: History
			},
			{
				path: 'question',
				name: 'Question',
				component: Question
			}, {
				path: 'AddOrEditQuestion',
				name: 'AddOrEditQuestion',
				props: true,
				component: AddOrEditQuestion
			},
		
			{
				path: '/redirect',
				component: () => import('../components/redirect.vue'),
				hidden: true
			},
			{
				path:'user',
				name:'User',
				component:User
			}
			// 	{
			// 		path: 'user',
			// 		name: 'User',
			// 		component: User
			// }
		]
	}
]

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
	// 检查目标路由是否需要认证
	const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
	const isAuthenticated = sessionStorage.getItem('token')

	if (requiresAuth) {
		if (isAuthenticated) {
			next() // 已登录则放行
		} else {
			next({
				path: '/',
				query: {
					redirect: to.fullPath
				} // 记录重定向路径
			})
		}
	} else {
		// 已登录用户禁止访问登录/注册页
		if ((to.path === '/register') && isAuthenticated) {
			next('/main/home')
		} else {
			next()
		}
	}
})

export default router
